package com.xnx3.kefu.admin.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.xnx3.j2ee.util.ActionLogUtil;
import com.xnx3.j2ee.service.SqlCacheService;
import com.xnx3.j2ee.service.SqlService;
import com.xnx3.j2ee.service.UserService;
import com.xnx3.j2ee.vo.BaseVO;
import com.xnx3.kefu.core.entity.Kefu;
import com.xnx3.kefu.core.vo.KefuVO;
import com.xnx3.kefu.admin.util.SessionUtil;

/**
 * 客服设置
 * @author 管雷鸣
 */
@Controller(value="KefuController")
@RequestMapping("/kefu/admin/kefu/")
public class KefuController extends BaseController {
	@Resource
	private SqlService sqlService;
	@Resource
	private SqlCacheService sqlCacheService;
	@Resource
	private UserService userService;
	

	/**
	 * 获取客服设置
	 */
	@ResponseBody
	@RequestMapping("getKefu${api.suffix}")
	public KefuVO getKefu(HttpServletRequest request){
		KefuVO vo = new KefuVO();
		Kefu kefu = getKefu();
		
		vo.setKefu(kefu);
		
		ActionLogUtil.insert(request,kefu.getId(), "打开客服设置页面");
		return vo;
	}

	/**
	 * 更改客服参数
	 * @param name {@link Kefu}驼峰字段名，传入如 use、autoReply、useOffLineEmail、email、offlineAutoReply 等
	 * @param value 值
	 */
	@RequestMapping("update${api.suffix}")
	@ResponseBody
	public BaseVO update(HttpServletRequest request,
			@RequestParam(value = "name", required = false , defaultValue="") String name,
			@RequestParam(value = "value", required = false , defaultValue="") String value){
		Kefu kefu = sqlService.findById(Kefu.class, getKefuId());
		
		if(name.equals("use")){
			kefu.setUseKefu(value.equals(Kefu.USE_TRUE+"") ? Kefu.USE_TRUE:Kefu.USE_FALSE);
		}else if(name.equals("autoReply")){
			value = filter(value);
			if(value.length() > 250){
				return error("内容限制在250个字符以内");
			}
			kefu.setAutoReply(value);
		}else if(name.equals("offlineAutoReply")){
			value = filter(value);
			if(value.length() > 250){
				return error("自动回复内容限制在250个字符以内");
			}
			kefu.setOfflineAutoRaply(value);
		}else if(name.equals("useOffLineEmail")){
			kefu.setUseOffLineEmail(value.equals(Kefu.USE_TRUE+"") ? Kefu.USE_TRUE : Kefu.USE_FALSE);
		}else if(name.equals("email")){
			kefu.setEmail(filter(value));
		}else{
			return error("您要修改哪项?");
		}
		
		sqlService.save(kefu);
		
		//刷新session缓存
		SessionUtil.setKefu(kefu);
		//清所有缓存
		sqlCacheService.deleteCacheById(Kefu.class, kefu.getId());
		
		ActionLogUtil.insert(request,kefu.getId(), "更改客服设置", kefu.toString());
		return success();
	}
	
	
}
